package com.wang.helloworld.storm.bolt;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;

public class MessageDeliveryBolt  extends BaseRichBolt{
	Logger logger = LoggerFactory.getLogger(MessageDeliveryBolt.class);
	
	private static final long serialVersionUID = -2011967394488119145L;
	
	OutputCollector collector;
	Map map;
	TopologyContext context;

	public void execute(Tuple tuple) {
		System.out.println("Receive message: " + new String(tuple.getBinary(0)));

		// We are interested in message 
		String message[] = new String(tuple.getBinary(0)).split("=");

		// Splite message to messageType and messageBody
		if(message[0].equals("command"))
		{
			collector.emit("processCommandMessage", new Values(message.length>1?message[1]:""));
		}
		else
		{
			collector.emit("processOtherMessage", new Values(message[0], message.length>1?message[1]:""));
		}

        collector.ack(tuple);
	}

	public void prepare(Map map, TopologyContext context, OutputCollector collector) {
		this.collector = collector;
		this.map = map;
		this.context = context;
	}

	public void declareOutputFields(OutputFieldsDeclarer declarer) {
		declarer.declareStream("processCommandMessage", new Fields("instruction"));
		declarer.declareStream("processOtherMessage",new Fields("messageType","data"));
	}

}
